package cn.zeal4j.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

/**
 * @author Administrator
 * @file IntelliJ IDEA Spring-Security-Tutorial
 * @create 2020 09 27 23:48
 * 前后端分离url登陆处理 Front and rear separation （FARS）
 */
public class FarsAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private String url;

    public FarsAuthenticationSuccessHandler(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // ip 地址获取
        String remoteAddr = httpServletRequest.getRemoteAddr();
        System.out.println(remoteAddr);


        Object principal = authentication.getPrincipal();
        User user = (User) principal;
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        for (GrantedAuthority authority : authorities) {
            System.out.println(authority.getAuthority());
        }

        httpServletResponse.sendRedirect(url);
    }

//    @Override
//    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
//
//    }
}
